<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MES智能助手 - 科大讯飞AI集成演示</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header p {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .chat-container {
            display: flex;
            height: 600px;
        }

        .chat-area {
            flex: 1;
            display: flex;
            flex-direction: column;
        }

        .messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            background: #f8f9fa;
        }

        .message {
            margin-bottom: 20px;
            max-width: 80%;
        }

        .message.user {
            margin-left: auto;
        }

        .message-content {
            padding: 15px 20px;
            border-radius: 18px;
            word-wrap: break-word;
            line-height: 1.5;
        }

        .message.user .message-content {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .message.assistant .message-content {
            background: white;
            border: 1px solid #e1e5e9;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }

        .message-time {
            font-size: 12px;
            color: #666;
            margin-top: 5px;
            text-align: right;
        }

        .message.assistant .message-time {
            text-align: left;
        }

        .input-area {
            padding: 20px;
            border-top: 1px solid #e1e5e9;
            background: white;
        }

        .input-group {
            display: flex;
            gap: 10px;
            align-items: center;
        }

        #user-input {
            flex: 1;
            padding: 15px;
            border: 2px solid #e1e5e9;
            border-radius: 25px;
            font-size: 16px;
            outline: none;
            transition: border-color 0.3s;
        }

        #user-input:focus {
            border-color: #667eea;
        }

        .send-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 50%;
            width: 50px;
            height: 50px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: transform 0.2s;
            font-size: 20px;
        }

        .send-btn:hover {
            transform: scale(1.1);
        }

        .suggestions {
            padding: 10px 20px;
            background: #f8f9fa;
            border-top: 1px solid #e1e5e9;
            display: none;
        }

        .suggestions.show {
            display: block;
        }

        .suggestion-btn {
            display: inline-block;
            margin: 5px;
            padding: 8px 16px;
            background: #e9ecef;
            color: #495057;
            border: 1px solid #ced4da;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .suggestion-btn:hover {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            transform: translateY(-2px);
        }

        .sidebar {
            width: 300px;
            background: #f8f9fa;
            border-left: 1px solid #e1e5e9;
            padding: 20px;
        }

        .sidebar h3 {
            color: #333;
            margin-bottom: 15px;
            font-size: 18px;
        }

        .quick-actions {
            list-style: none;
        }

        .quick-actions li {
            margin-bottom: 10px;
        }

        .quick-action-btn {
            width: 100%;
            padding: 12px;
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s;
            text-align: left;
            font-size: 14px;
        }

        .quick-action-btn:hover {
            background: #e9ecef;
            transform: translateX(5px);
        }

        .status {
            margin-top: 30px;
            padding: 15px;
            background: white;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }

        .status-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }

        .typing-indicator {
            display: none;
            align-items: center;
            padding: 15px 20px;
            background: white;
            border-radius: 18px;
            margin-bottom: 20px;
            max-width: 80px;
        }

        .typing-indicator.show {
            display: flex;
        }

        .typing-dots {
            display: flex;
            gap: 4px;
        }

        .typing-dot {
            width: 8px;
            height: 8px;
            background: #666;
            border-radius: 50%;
            animation: typing 1.4s infinite ease-in-out;
        }

        .typing-dot:nth-child(2) {
            animation-delay: 0.2s;
        }

        .typing-dot:nth-child(3) {
            animation-delay: 0.4s;
        }

        @keyframes typing {
            0%, 60%, 100% {
                transform: translateY(0);
            }
            30% {
                transform: translateY(-10px);
            }
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
            border-radius: 8px;
            padding: 10px;
            margin-top: 10px;
        }

        @media (max-width: 768px) {
            .chat-container {
                flex-direction: column;
                height: auto;
            }

            .sidebar {
                width: 100%;
                order: -1;
            }

            .messages {
                height: 400px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🤖 MES智能助手</h1>
            <p>基于科大讯飞AI的智能制造执行系统助手</p>
        </div>

        <div class="chat-container">
            <div class="chat-area">
                <div class="messages" id="messages">
                    <div class="message assistant">
                        <div class="message-content">
                            👋 您好！我是MES制造执行系统的智能助手。我可以帮助您：
                            <br><br>
                            📋 查询工单信息<br>
                            📦 查看物料资料<br>
                            🏢 查询客户信息<br>
                            🏗️ 查看仓库状态<br>
                            📊 查看系统统计<br>
                            <br>
                            请告诉我您需要什么帮助！
                        </div>
                        <div class="message-time">系统助手</div>
                    </div>
                </div>

                <div class="suggestions" id="suggestions">
                    <!-- 建议按钮将动态添加到这里 -->
                </div>

                <div class="input-area">
                    <div class="input-group">
                        <input type="text" id="user-input" placeholder="请输入您的问题..." autocomplete="off">
                        <button class="send-btn" onclick="sendMessage()">📤</button>
                    </div>
                </div>
            </div>

            <div class="sidebar">
                <h3>🚀 快速操作</h3>
                <ul class="quick-actions">
                    <li><button class="quick-action-btn" onclick="quickQuery('查询工单信息')">📋 查询工单</button></li>
                    <li><button class="quick-action-btn" onclick="quickQuery('查看物料信息')">📦 查看物料</button></li>
                    <li><button class="quick-action-btn" onclick="quickQuery('查询客户信息')">🏢 查询客户</button></li>
                    <li><button class="quick-action-btn" onclick="quickQuery('查看仓库状态')">🏗️ 查看仓库</button></li>
                    <li><button class="quick-action-btn" onclick="quickQuery('系统统计数据')">📊 系统统计</button></li>
                    <li><button class="quick-action-btn" onclick="quickQuery('今天有多少工单？')">📈 今日工单</button></li>
                </ul>

                <div class="status">
                    <h3>📡 连接状态</h3>
                    <div class="status-item">
                        <span>AI服务</span>
                        <span id="ai-status">🟢 在线</span>
                    </div>
                    <div class="status-item">
                        <span>会话ID</span>
                        <span id="session-id">-</span>
                    </div>
                    <div class="status-item">
                        <span>响应时间</span>
                        <span id="response-time">-</span>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        class AIAssistant {
            constructor() {
                this.baseUrl = window.location.origin;
                this.sessionId = this.generateSessionId();
                this.history = [];
                this.init();
            }

            init() {
                // 显示会话ID
                document.getElementById('session-id').textContent = this.sessionId.slice(-8);
                
                // 绑定回车键
                document.getElementById('user-input').addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        this.sendMessage();
                    }
                });

                // 检查AI服务状态
                this.checkHealth();
            }

            async checkHealth() {
                try {
                    const response = await fetch(`${this.baseUrl}/api/AIAssistant/HealthCheck`);
                    const result = await response.json();
                    
                    const statusElement = document.getElementById('ai-status');
                    if (result.code === 0) {
                        statusElement.textContent = '🟢 在线';
                        statusElement.style.color = 'green';
                    } else {
                        statusElement.textContent = '🔴 离线';
                        statusElement.style.color = 'red';
                    }
                } catch (error) {
                    document.getElementById('ai-status').textContent = '🔴 离线';
                    document.getElementById('ai-status').style.color = 'red';
                    console.error('健康检查失败:', error);
                }
            }

            async sendMessage() {
                const input = document.getElementById('user-input');
                const message = input.value.trim();
                
                if (!message) return;
                
                input.value = '';
                this.addMessage('user', message);
                this.showTypingIndicator();
                
                const startTime = Date.now();
                
                try {
                    const response = await fetch(`${this.baseUrl}/api/AIAssistant/Chat`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            message: message,
                            sessionId: this.sessionId,
                            userId: 1,
                            history: this.history.slice(-10)
                        })
                    });

                    const result = await response.json();
                    const responseTime = Date.now() - startTime;
                    
                    this.hideTypingIndicator();
                    
                    if (result.code === 0) {
                        this.addMessage('assistant', result.data.response);
                        this.updateHistory('user', message);
                        this.updateHistory('assistant', result.data.response);
                        this.showSuggestions(result.data.suggestions);
                        this.updateResponseTime(responseTime);
                    } else {
                        this.addMessage('assistant', `抱歉，出现了错误：${result.msg}`);
                        this.showError(result.msg);
                    }
                } catch (error) {
                    this.hideTypingIndicator();
                    this.addMessage('assistant', '抱歉，AI助手暂时无法响应，请稍后再试。');
                    this.showError(error.message);
                    console.error('发送消息失败:', error);
                }
            }

            addMessage(role, content) {
                const messagesContainer = document.getElementById('messages');
                const messageDiv = document.createElement('div');
                messageDiv.className = `message ${role}`;
                
                const now = new Date();
                const timeString = now.toLocaleTimeString('zh-CN', { 
                    hour: '2-digit', 
                    minute: '2-digit' 
                });
                
                messageDiv.innerHTML = `
                    <div class="message-content">${this.formatMessage(content)}</div>
                    <div class="message-time">${timeString}</div>
                `;
                
                messagesContainer.appendChild(messageDiv);
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }

            formatMessage(content) {
                // 简单的格式化，支持换行和基本的表情符号
                return content
                    .replace(/\n/g, '<br>')
                    .replace(/📋/g, '📋')
                    .replace(/📦/g, '📦')
                    .replace(/🏢/g, '🏢')
                    .replace(/🏗️/g, '🏗️')
                    .replace(/📊/g, '📊')
                    .replace(/📈/g, '📈')
                    .replace(/💼/g, '💼');
            }

            showTypingIndicator() {
                const messagesContainer = document.getElementById('messages');
                const typingDiv = document.createElement('div');
                typingDiv.className = 'typing-indicator show';
                typingDiv.id = 'typing-indicator';
                typingDiv.innerHTML = `
                    <div class="typing-dots">
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                        <div class="typing-dot"></div>
                    </div>
                `;
                messagesContainer.appendChild(typingDiv);
                messagesContainer.scrollTop = messagesContainer.scrollHeight;
            }

            hideTypingIndicator() {
                const typingIndicator = document.getElementById('typing-indicator');
                if (typingIndicator) {
                    typingIndicator.remove();
                }
            }

            showSuggestions(suggestions) {
                const suggestionsContainer = document.getElementById('suggestions');
                suggestionsContainer.innerHTML = '';
                
                if (suggestions && suggestions.length > 0) {
                    suggestions.forEach(suggestion => {
                        const button = document.createElement('button');
                        button.className = 'suggestion-btn';
                        button.textContent = suggestion;
                        button.onclick = () => this.handleSuggestion(suggestion);
                        suggestionsContainer.appendChild(button);
                    });
                    suggestionsContainer.classList.add('show');
                } else {
                    suggestionsContainer.classList.remove('show');
                }
            }

            handleSuggestion(suggestion) {
                document.getElementById('user-input').value = suggestion;
                this.sendMessage();
            }

            updateHistory(role, content) {
                this.history.push({
                    role: role,
                    content: content,
                    timestamp: new Date().toISOString()
                });
                
                // 保持历史记录在合理长度
                if (this.history.length > 20) {
                    this.history = this.history.slice(-20);
                }
            }

            updateResponseTime(time) {
                document.getElementById('response-time').textContent = `${time}ms`;
            }

            showError(message) {
                const messagesContainer = document.getElementById('messages');
                const errorDiv = document.createElement('div');
                errorDiv.className = 'error-message';
                errorDiv.textContent = `错误: ${message}`;
                messagesContainer.appendChild(errorDiv);
                
                // 5秒后自动移除错误消息
                setTimeout(() => {
                    errorDiv.remove();
                }, 5000);
            }

            generateSessionId() {
                return 'web-session-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
            }
        }

        // 初始化AI助手
        const aiAssistant = new AIAssistant();

        // 全局函数
        function sendMessage() {
            aiAssistant.sendMessage();
        }

        function quickQuery(query) {
            document.getElementById('user-input').value = query;
            aiAssistant.sendMessage();
        }

        // 页面加载完成后的欢迎消息
        window.addEventListener('load', () => {
            console.log('🤖 MES智能助手已启动');
            console.log('基于科大讯飞AI技术');
            console.log('会话ID:', aiAssistant.sessionId);
        });
    </script>
</body>
</html>

